package cn.com.miao.lynx.plugin.storage;

import cn.com.miao.lynx.plugin.storage.progress.ObjectStorageProgress;
import cn.com.miao.lynx.plugin.storage.properties.LocalStorageProperties;
import cn.com.miao.lynx.plugin.storage.properties.OssProperties;
import cn.com.miao.lynx.plugin.storage.service.StorageService;
import cn.com.miao.lynx.plugin.storage.service.impl.LocalStorageService;
import cn.com.miao.lynx.plugin.storage.service.impl.OssStorageService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;

/**
 * StorageAutoConfig
 *
 * @title: StorageAutoConfig
 * @description:
 * @author: dengmiao
 * @create: 2020-01-10 14:38
 **/
@Slf4j
@AllArgsConstructor
@Configuration
@EnableConfigurationProperties({OssProperties.class, LocalStorageProperties.class})
public class StorageAutoConfig {

    private final OssProperties ossProperties;

    private final ObjectProvider<ObjectStorageProgress> objectStorageProgressObjectProvider;

    private final LocalStorageProperties localStorageProperties;

    @Bean
    @ConditionalOnProperty(prefix = "lynx.storage", name = "type", havingValue = "aliyun" )
    @ConditionalOnMissingBean(StorageService.class)
    @Order(0)
    public OssStorageService apiBootOssService() {
        return OssStorageService.builder()
                .endpoint(ossProperties.getRegion().getEndpoint())
                .bucketName(ossProperties.getBucketName())
                .accessKeyId(ossProperties.getAccessKeyId())
                .accessKeySecret(ossProperties.getAccessKeySecret())
                .domain(ossProperties.getDomain())
                .objectStorageProgress(objectStorageProgressObjectProvider.getIfAvailable())
                .build();
    }

    @Bean
    @ConditionalOnProperty(prefix = "lynx.storage", name = "type", havingValue = "local" )
    @ConditionalOnMissingBean(StorageService.class)
    @Order(1)
    public LocalStorageService localFileStorage() {
        return new LocalStorageService(localStorageProperties.getLocation());
    }

    @Bean
    @Order(2)
    @ConditionalOnMissingBean(StorageService.class)
    public LocalStorageService defaultLocalStorage() {
        return new LocalStorageService();
    }
}
